//
//  DMNativeAdManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/7/9.
//

#import "DMNativeAdManager.h"
#import "NativeAdView.h"
@import UIKit;
#import "../../Utils/Logger/IMLogUtils.h"
#import "DMThinkingManager.h"

@interface DMNativeAdManager ()<LevelPlayNativeAdDelegate>

@property (nonatomic, strong) LevelPlayNativeAd  *nativeAd;
@property (nonatomic, strong) UIView             *containerView;
@property (nonatomic, weak)   UIViewController   *currentVC;
@property (nonatomic, strong) NSString           *currentScene;

@end

@implementation DMNativeAdManager

+ (instancetype)sharedInstance {
    static DMNativeAdManager *inst;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        inst = [[self alloc] init];
    });
    return inst;
}

#pragma mark - Public

- (void)setCurrentScene:(NSString *)scene {
    self.currentScene = scene;
}

- (void)initWithNativead {
    [self loadNativeAd];
   [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] ========== 开始初始化原生广告 =========="]; 
}
- (void)loadNativeAd {
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] ========== 开始加载原生广告 =========="];
    
    // 埋点：SDK_ad_fill_request 广告预加载事件打点
    NSDictionary *fillRequestParams = @{
        @"w_ad_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
        @"w_ad_type": @"native",
        @"w_ad_unit_id": @"native_ironsource_default"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] 事件打点: SDK_ad_fill_request"];
    
    // 1. 销毁旧广告
    [self destroyNativeAd];
    
    // 2. 创建并加载新广告
    UIViewController *vc = [self topMostViewController];
    LevelPlayNativeAd *ad = [[[[[LevelPlayNativeAdBuilder new]
                                withViewController:vc]
                               withPlacementName:@"DEFAULT_NATIVE_SCENE"]
                              withDelegate:self]
                             build];
    self.nativeAd = ad;
    [ad loadAd];
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] 开始加载原生广告..."];
}

- (void)renderAdToContainer:(UIView *)containerView {
    if (!containerView) {
        [IMLogUtils warning:IMLogTagAd format:@"📰 [IronSource Native] ❌ 容器视图为空，无法渲染广告"];
        return;
    }
    
    self.containerView = containerView;
    
    // 埋点：SDK_ad_show_request 广告展示请求事件打点
    NSDictionary *showRequestParams = @{
        @"w_ad_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
        @"w_ad_type": @"native"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] 事件打点: SDK_ad_show_request"];
    
    // 如果广告已加载，立即渲染
    if (self.nativeAd) {
        [self renderAd];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] 广告尚未加载，等待加载完成后渲染"];
    }
}

- (void)destroyNativeAd {
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] 💥 销毁原生广告"];
    
    if (self.nativeAd) {
        [self.nativeAd destroyAd];
        self.nativeAd = nil;
    }
    
    if (self.containerView) {
        [self.containerView removeFromSuperview];
        self.containerView = nil;
    }
}

#pragma mark - LevelPlayNativeAdDelegate

- (void)didLoad:(LevelPlayNativeAd *)nativeAd withAdInfo:(ISAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 原生广告加载成功"];
    
    // 埋点：SDK_ad_fill_success 广告预加载成功事件打点
    NSDictionary *fillSuccessParams = @{
        @"w_ad_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
        @"w_ad_type": @"native",
        @"w_ad_unit_id": adInfo.instance_id ?: @"native_ironsource_default",
        @"w_network": adInfo.ad_network ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
    [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 事件打点: SDK_ad_fill_success"];
    
    // 通知DMAdDelegate加载成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadNativeForScene:adId:)]) {
        [self.delegate dmAdManager:nil didLoadNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" adId:adInfo.instance_id ?: @"unknown"];
    }
    
    // 加载成功后，如果外部已经调用 show，就立即渲染
    if (self.containerView) {
        [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 检测到待展示请求，立即渲染广告"];
        [self renderAd];
    }
}

- (void)didFailToLoad:(LevelPlayNativeAd *)nativeAd withError:(NSError *)error {
    [IMLogUtils error:IMLogTagNative format:@"📰 [IronSource Native] 原生广告加载失败: %@", error.localizedDescription];
    
    // 埋点：SDK_ad_fill_fail 广告预加载失败事件打点
    NSDictionary *fillFailParams = @{
        @"w_ad_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
        @"w_ad_type": @"native",
        @"w_ad_unit_id": @"native_ironsource_default",
        @"w_error_code": @(error.code),
        @"w_error_msg": error.localizedDescription ?: @"原生广告加载失败"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
    [IMLogUtils error:IMLogTagNative format:@"📰 [IronSource Native] 事件打点: SDK_ad_fill_fail"];
    
    // 通知DMAdDelegate加载失败
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadNativeForScene:error:)]) {
        [self.delegate dmAdManager:nil didFailToLoadNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" error:error];
    }
}

- (void)didRecordImpression:(LevelPlayNativeAd *)nativeAd withAdInfo:(ISAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 原生广告展示成功"];
    
    // 埋点：SDK_ad_show_success 广告展示成功事件打点
    NSDictionary *showSuccessParams = @{
        @"w_ad_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
        @"w_ad_type": @"native",
        @"w_ad_unit_id": adInfo.instance_id ?: @"native_ironsource_default",
        @"w_network": adInfo.ad_network ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
    [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 事件打点: SDK_ad_show_success"];
    // 新增 AD_Native_show 埋点
    {
        double ecpm = adInfo.revenue ? adInfo.revenue.doubleValue * 1000.0 : 0.0;
        NSDictionary *nativeShowParams = @{
            @"w_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
            @"w_revenue": @(ecpm)
        };
        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"AD_Native_show" jsonStr:nativeShowParams];
        [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 事件打点: AD_Native_show, w_revenue: %.2f", ecpm];
    }
    
    // 通知DMAdDelegate展示成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowNativeForScene:adId:)]) {
        [self.delegate dmAdManager:nil didShowNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" adId:adInfo.instance_id ?: @"unknown"];
    }
}

- (void)didClick:(LevelPlayNativeAd *)nativeAd withAdInfo:(ISAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 原生广告被点击"];
    
    // 埋点：SDK_ad_show_click 广告点击事件打点
    NSDictionary *clickParams = @{
        @"w_ad_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
        @"w_ad_type": @"native",
        @"w_ad_unit_id": adInfo.instance_id ?: @"native_ironsource_default",
        @"w_network": adInfo.ad_network ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
    [IMLogUtils info:IMLogTagNative format:@"📰 [IronSource Native] 事件打点: SDK_ad_show_click"];
    
    // 通知DMAdDelegate点击事件
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickNativeForScene:adId:)]) {
        [self.delegate dmAdManager:nil didClickNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" adId:adInfo.instance_id ?: @"unknown"];
    }
}

#pragma mark - Private

/// 渲染到容器（内部方法）
- (void)renderAd {
    if (!self.nativeAd || !self.containerView) {
        [IMLogUtils warning:IMLogTagAd format:@"📰 [IronSource Native] ❌ 无法渲染：广告或容器为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] 开始渲染原生广告"];
    
    // 清理旧视图
    [self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    // 创建并添加 NativeAdView
    NativeAdView *adView = [[NativeAdView alloc] initWithNativeAd:self.nativeAd];
    adView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:adView];
    
    // 设置约束
    [NSLayoutConstraint activateConstraints:@[
        [adView.topAnchor constraintEqualToAnchor:self.containerView.topAnchor],
        [adView.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor],
        [adView.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor],
        [adView.bottomAnchor constraintEqualToAnchor:self.containerView.bottomAnchor],
    ]];
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [IronSource Native] ✅ 原生广告渲染完成"];
}

/// 获取最顶层的 UIViewController
- (UIViewController *)topMostViewController {
    UIWindow *keyWindow = nil;
    for (UIWindow *w in [UIApplication sharedApplication].windows) {
        if (w.isKeyWindow) { keyWindow = w; break; }
    }
    if (!keyWindow) keyWindow = [UIApplication sharedApplication].delegate.window;
    return [self _topFrom: keyWindow.rootViewController];
}

- (UIViewController *)_topFrom:(UIViewController *)vc {
    if (vc.presentedViewController) {
        return [self _topFrom:vc.presentedViewController];
    } else if ([vc isKindOfClass:UINavigationController.class]) {
        return [self _topFrom:((UINavigationController*)vc).visibleViewController];
    } else if ([vc isKindOfClass:UITabBarController.class]) {
        return [self _topFrom:((UITabBarController*)vc).selectedViewController];
    }
    return vc;
}

@end
